import React, { Component } from "react";
import { InputItem, Toast } from "antd-mobile";
import MainLayout from "../../../component/mainLayout/mainLayout";
import SendMSGCode from "../../../component/sendMSGCode/sendMSGCode";
import yhTools from "../../../tools/yh";
import { channelCode, InterfaceG } from "../../../config/Config";
import "./TransferXHBOutByPay.scss";

class TransferXHBOutByPay extends Component {
	constructor(props) {
		super(props);

		this.state = {
			loadStatus: "1", //'0'：数据加载中，'1'：加载完成，'2'：加载失败
			/** 转出金额 */
			principal: "",
			/** 是否显示发送短信 */
			showMsgBox: false,
			/** 短信流水号 */
			messageSerialNumber: "",
			totalAmount: "",
			sceneId: "",
			phoneNumber: "",
			usableAmount: "",
			tradeNumber: "",
			holdDays: 0,
			advanceRate: 0,
			profitAmt: "0.00",
			totalAmt: "0.00",
			/** 部分支取最小金额 */
			remainingMoney: 0,
			/** 错误信息 */
			errmsg: ""
		};
		/** 是否已经点击提交按钮 */
		this.isSubmit = false;
	}

	componentDidMount() {
		this.initData();
	}

	/** 初始化 */
	async initData() {
		let { productId } = this.props.match.params;
		let objs = {
			url: InterfaceG.oneKeyRollOutInit,
			params: {
				channelCode: "YHB",
				productId
			},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			let pageData = res.data;
			this.setState({ ...pageData });
		} else {
			Toast.info(res.message, 2);
		}
	}
	/** 检测输入值,返回错误信息 */
	checkInput(inputValue) {
		let { remainingMoney, usableAmount } = this.state;
		if (
			inputValue.toString().substr(inputValue.toString().length - 1, 1) === "."
		) {
			return "请输入正确金额";
		} else if (
			usableAmount - Number(inputValue) < Number(remainingMoney) &&
			usableAmount - Number(inputValue) != 0
		) {
			// 如果不是全部支取 && 留存金额低于50
			if (Number(usableAmount) - Number(inputValue) < 0) {
				return `最大可支取的金额为${usableAmount}元`;
			} else {
				return `单笔存单留存金额不得少于${remainingMoney}元`;
			}
		} else {
			return "";
		}
	}

	onChangeInput(value) {
		let principal = value;
		let preValue = this.state.principal;
		let reg = /^(([1-9]\d*)|0)(\.\d{0,2}?)?$/;
		if (value && !reg.test(value)) {
			if (value === ".") {
				principal = "0.";
			} else {
				principal = preValue;
			}
		}
		let errmsg = this.checkInput(principal);

		this.setState({ principal, errmsg });
		// 正常
		if (!errmsg) {
			this.getProfitAmt(principal);
		}
	}

	/**短信验证码验证接口*/
	sendYzm() {
		let objs = {
			url: InterfaceG.getSmsCode,
			params: {
				channelCode: channelCode,
				operateType: "5",
				bindTel: this.state.phoneNumber
			},
			_alertShow: false
		};
		// Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code == "0" || res.code == "30022") {
				if (res.code == "30022") {
					Toast.info(res.message, 2);
				}
				this.sendCode.countdown();
				this.setState(
					{
						messageSerialNumber: res.data.messageSerialNumber,
						showMsgBox: true //显示验证码
					},
					() => {
						this.isSubmit = false;
					}
				);
			} else {
				this.isSubmit = false;
				Toast.info(res.message, 2);
			}
		});
	}
	/**利息计算 */
	getProfitAmt = inputValue => {
		const { advanceRate, holdDays } = this.state;

		//提前支取试算收益=支取本金*0.4%*实际持有天数（算头不算尾）/360
		let profitAmt = (
			(((parseFloat(inputValue) * parseFloat(advanceRate)) / 100) *
				parseFloat(holdDays)) /
			360
		).toFixed(2); //向上取整
		let totalAmt = (parseFloat(inputValue) + parseFloat(profitAmt)).toFixed(2);

		this.setState({
			profitAmt,
			totalAmt
		});
	};
	/** 提交 */
	async onSubmit() {
		let { principal, errmsg } = this.state;
		if (
			!errmsg &&
			principal &&
			Number(this.state.principal) > 0 &&
			!this.isSubmit
		) {
			this.isSubmit = true;
			this.sendYzm();
		}
	}

	/** 验证码输入后的回调 */
	async sendCodeCB(activeCode) {
		let { productId } = this.props.match.params;
		let {
			principal,
			messageSerialNumber,
			tradeNumber,
			sceneId,
			totalAmount
		} = this.state;
		let objs = {
			url: InterfaceG.oneKeyRollOutCommit,
			params: {
				channelCode: channelCode,
				principal,
				activeCode,
				messageSerialNumber,
				sceneId,
				productId,
				tradeNumber,
				totalAmount
			},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		if (res.code == "0") {
			this.props.history.push({
				pathname: `/transferXHBSuccess/out/${JSON.stringify({
					tradeAmount: res.data.outAmount,
					totalAmount: res.data.totalAmount
				})}`
			});
		} else {
			Toast.info(res.message, 2);
		}
	}
	/**全部转出 */
	transferOutAllClick() {
		const { usableAmount } = this.state;
		this.setState({ principal: usableAmount, errmsg: "" });
		this.getProfitAmt(usableAmount);
	}
	render() {
		const _pageParams = {
			header: {
				title: "转出小辉宝"
			},
			history: this.props.history,
			loadStatus: this.state.loadStatus,
			cacheLifecycles: this.props.cacheLifecycles
		};

		let {
			showMsgBox,
			phoneNumber,
			profitAmt,
			totalAmt,
			errmsg,
			principal
		} = this.state;

		let isSubmit =
			!this.state.errmsg &&
			this.state.principal &&
			Number(this.state.principal) > 0;

		return (
			<MainLayout pageParams={_pageParams}>
				<div className="transferXHBOutByPay">
					<div className="top">
						<img src={require("../../../images/imageXHB/jine.png")} alt="" />
						<div className="top-right">
							<p>
								小辉宝<span> (2019/11/01 转入)</span>
							</p>
							<div className="top-jine">
								<span>持有金额：{this.state.totalAmount}元</span>
								<span>可用金额：{this.state.usableAmount}元</span>
							</div>
						</div>
					</div>
					<div className="content">
						<div className="label">转出金额</div>
						<div className="money">
							<InputItem
								type="money"
								placeholder="请输入转出金额"
								onChange={v => this.onChangeInput(v)}
								editable
								value={this.state.principal}
								clear
								moneyKeyboardAlign="left"
								extra={
									<div
										className="all"
										onClick={this.transferOutAllClick.bind(this)}
									>
										全部转出
									</div>
								}
							>
								¥
							</InputItem>
							{this.state.errmsg && (
								<div className="errormsg">{this.state.errmsg}</div>
							)}
						</div>
						{/* <div className="money">
                            <b>¥</b>
                            <input type="number" placeholder="0.00" value={this.state.principal} onChange={e=>this.onChangeInput(e)}/>
                            <div className="all" onClick={()=>this.setState({principal:this.state.usableAmount})}>全部转出</div>
                        </div> */}
						<div className="tips">
							{errmsg || !principal ? (
								<span>部分支取时，留存金额不低于50.00元</span>
							) : (
								<div className="estimate-box">
									预计到账金额：
									<span className="estimate-money">¥{totalAmt}元</span>
									&nbsp;&nbsp;&nbsp;&nbsp;预计利息金额：
									<span className="estimate-money">¥{profitAmt}</span>
								</div>
							)}
						</div>
					</div>

					<div className="bottom-tips">
						<span>转出说明:</span>
						<p>
							1.转入日至下周一期间不可转出，观察期最长为7天，利息按照存款利率每周一发放，若转出未满一个周期，则该部分按活期利率计算利息。
						</p>
						<p>
							2.每日23:50至次日0:20（每周日23:00-每周一3:00）因银行及平台系统原因，转入、转出均关闭，其他时间正常。
						</p>
					</div>

					<div
						className="btn"
						style={{ opacity: isSubmit ? 1 : 0.15 }}
						onClick={() => this.onSubmit()}
					>
						确认转出
					</div>
				</div>

				<SendMSGCode
					ref={ref => {
						this.sendCode = ref;
					}}
					getYZMCode={this.sendYzm.bind(this)}
					sendSuccessPhone={yhTools.handelInfo(phoneNumber, 3, 4)}
					submitCode={this.sendCodeCB.bind(this)}
					closeSendModal={() => this.setState({ showMsgBox: false })}
					showMsgBox={showMsgBox}
					seconds={60}
				/>
			</MainLayout>
		);
	}
}

export default TransferXHBOutByPay;
